<template>
  <div class="metal-transaction-container">
    <!-- Replace el-row with a flex container -->
    <div style="display: flex; height: 100%; gap: 2px;">
      <!-- Left: Customer List (fixed width) -->
      <div style="flex: 0 0 160px;">
        <el-col class="customer-list-panel">
          <!-- Historical Records Dropdown -->
          <div class="period-history-section">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <div class="section-title">历史记录</div>
              <el-button icon="Refresh" circle size="small" @click="refreshPeriodRecordList"></el-button>
            </div>
            <el-select v-model="selectedPeriodId" placeholder="请选择历史记录" size="small" clearable
              @change="handlePeriodSelect" style="width: 100%; margin-bottom: 10px;">
              <el-option v-for="(period, index) in periodOrderList" :key="period.id" :label="formatPeriodLabel(period)"
                :value="period.id">
                <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                  <span>{{ formatPeriodLabel(period) }}</span>
                  <el-button v-if="index === periodOrderList.length - 1" type="danger" size="mini"
                    @click.stop="cancelLastPeriod(period)" style="margin-left: 10px;">
                    撤销
                  </el-button>
                </div>
              </el-option>
            </el-select>
          </div>

          <el-card class="customer-list-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span>客户列表</span>
                <el-button icon="Refresh" circle size="small" @click="refreshData"></el-button>
              </div>
            </template>

            <div class="customer-search">
              <el-input v-model="customerFilter" placeholder="搜索客户..." clearable :loading="searchLoading"
                @input="handleCustomerSearch">
                <template #prefix>
                  <i class="el-input__icon el-icon-search"></i>
                </template>
              </el-input>
            </div>

            <el-scrollbar class="customer-scrollbar">
              <el-menu :default-active="selectedCustomerId" class="customer-menu" @select="handleCustomerSelect">
                <el-menu-item v-for="customer in customerList" :key="customer.id" :index="customer.id">
                  <i class="el-icon-user"></i>
                  <span>{{ customer.name }}</span>
                </el-menu-item>
              </el-menu>
            </el-scrollbar>

            <!-- Pagination for customer list -->
            <div class="customer-pagination">
              <el-pagination small layout="prev, pager, next" :total="customerTotal" :page-size="customerPageSize"
                :current-page="customerPage" @current-change="handleCustomerPageChange" />
            </div>
          </el-card>

          <!-- Settlement Section -->
          <div class="settlement-section">
            <el-button type="primary" size="small" style="width: 100%;" @click="handleSettlement">
              结算
            </el-button>
          </div>
        </el-col>
      </div>

      <!-- Right: Transaction Records (flex to fill remaining space) -->
      <div style="flex: 1; overflow: hidden;">
        <el-col class="transaction-panel">
          <!-- Set fixed container with scrollable content -->
          <div
            style="background-color: #ffffff; height: 100%; overflow: hidden; display: flex; flex-direction: column;">
            <div v-if="selectedCustomer" class="transaction-content" style="flex: 1; overflow: auto;">

              <customer-transaction-excel-page ref="excelPage" />

            </div>

            <div v-else class="empty-placeholder"
              style="flex: 1; display: flex; align-items: center; justify-content: center;">
              <el-empty description="请选择客户查看交易记录"></el-empty>
            </div>
          </div>
        </el-col>
      </div>
    </div>

    <!-- Settlement Dialog -->
    <settlement-dialog v-model="settlementDialogVisible" @start-settlement="onStartSettlement" @close="onDialogClose" />

  </div>

</template>

<script>
import { ElMessage } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { TargetObjectFilter, TargetObjectType, TargetObjectPlatformType } from '../../public/engine/targetOrg/targetObject'
import { DataPage } from '../../public/network/communicationConverter'
//import CustomerTransactionPage from './customerTransactionsPage.vue'
import customerTransactionExcelPage from './customerTransactionExcelPage.vue'
import { deleteTargetObjectNetworkCache,deletePeriodSettleNetworkCache } from '../../public/network/api'
import { Definition } from '../../public/engine/common/definition'
import { PeriodSettlementUiAction } from '../../public/engine/uiAction/periodSettlementUiAction'
//import { debounce } from '../../public/utils/util'
import SettlementDialog from './settlementDialog.vue'
import { ElMessageBox } from 'element-plus'
import { PeriodSettlementOrder } from '../../public/engine/periodSettlement/periodSettlementOrder'

export default {
  name: 'mtransactions',

  components: {
    // CustomerTransactionPage,
    customerTransactionExcelPage,
    SettlementDialog
  },

  data() {
    return {
      basicUiAction: new BasicUiAction(),
      settlementUiAction: new PeriodSettlementUiAction(),
      customerList: [],
      customerFilter: '',
      selectedCustomerId: '',
      loading: false,
      searchLoading: false,
      filter: new TargetObjectFilter({enable : true}),

      // Pagination for customer list
      customerPage: 1,
      customerPageSize: 200,
      customerTotal: 0,

      // Debounce for search
      debouncedSearch: null,

      periodOrderList: [],
      selectedPeriodId: '', // Added for period selection

      // Settlement dialog
      settlementDialogVisible: false
    }
  },

  watch: {
    // Watch for changes in selectedCustomer
    selectedCustomerId: {
      handler(customerId) {

        if (customerId && this.$refs.excelPage) {
          // Call the updateTargetObj method on the child component

          //console.log('Updating selected customerId:', customerId);
          //console.log('Updating selected selectedCustomer:', this.selectedCustomer);
          this.$refs.excelPage.updateTargetObj(this.selectedCustomer);
        }
      },
      immediate: true // Trigger on initial load as well
    }
  },

  computed: {
    selectedCustomer() {
      return this.customerList.find(customer => customer.id === this.selectedCustomerId)
    }
  },

  async mounted() {
    // Initialize filter
    this.filter.objType = null;
    this.filter.objPlatformType = TargetObjectPlatformType.TUserCreated;

    // Create debounced search function
    //this.debouncedSearch = debounce(this.loadCustomerList, 300);
    this.debouncedSearch = this.loadCustomerList;

    // Load initial customer list
    await this.loadCustomerList()

    // 加载历史结算记录
    this.loadPeriodList();

    // 加载好后通知更新客户，watch 监控在第一次初始化时没有触发
    this.$refs.excelPage.updateTargetObj(this.selectedCustomer);
  },

  methods: {

    async refreshPeriodRecordList(){
      deletePeriodSettleNetworkCache();
      this.refreshData();
    },
    async refreshData() {
      deleteTargetObjectNetworkCache();
      this.customerPage = 1;
      await this.loadCustomerList()
      this.loadPeriodList();
    },

    async loadCustomerList() {
      this.searchLoading = true
      try {
        // Update filter with search term
        this.filter.mixedLikeInfo = this.customerFilter || ''

        const res = await this.basicUiAction.getTargetObjectData({
          pageInfo: new DataPage(this.customerPage, 0, this.customerPageSize),
          filter: this.filter.toJson()
        })

        if (res?.data?.dataList) {
          this.customerList = res.data.dataList
          this.customerTotal = Number(res.data.pageInfo?.total || res.data.dataList.length)

          // Select the first customer by default if none selected
          if (this.customerList.length > 0 && !this.selectedCustomerId) {
            this.selectedCustomerId = this.customerList[0].id
          }

          //console.log('Customer List:', this.customerList)
        } else {
          ElMessage.error('获取客户列表失败')
        }
      } catch (error) {
        console.error('获取客户列表失败:', error)
        ElMessage.error('获取客户列表失败')
      } finally {
        this.searchLoading = false
      }
    },

    // 加载结算列表
    async loadPeriodList() {
      try {
        const res = await this.settlementUiAction.getPeriodSettlementData({
          pageInfo: new DataPage(1, 0, 24),
          filter: null
        })

        if (res?.data?.dataList) {
          this.periodOrderList = res.data.dataList

          console.log('periodOrderList:', this.periodOrderList)
        } else {
          ElMessage.error('获取历史计算记录列表失败')
        }
      } catch (error) {
        console.error('获取历史计算记录列表失败:', error)
      }
    },

    // 取消结算周期
    cancelLastPeriod(period) {
      console.log('Canceling period:', period);
      // TODO: Implement actual cancellation logic here
      ElMessageBox.confirm(
        '确定要取消这个结算周期吗？取消将会删除该周期期初记录，但是不会删除普通记录,周期将会自动回滚到上一个结算周期。 如果当前期初记录有变更过存欠款，存欠料，需要自行处理变更数据。',
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
         // type: 'warning',
        }
      ).then(async () => {
        // Actual cancellation logic would go here
        //ElMessage.success('已取消结算周期');        

        let order = PeriodSettlementOrder.empty();
        order.id = period.id;

        let ret = await this.settlementUiAction.removeSettleCombineOrder(order);

        // Actual settlement logic would go here
        if (ret != null) {
          this.loadPeriodList();
          this.$refs.excelPage.updateTargetObj(this.selectedCustomer,true);
          ElMessage.success('删除结算成功');          
        }

      }).catch(() => {
        // User cancelled the operation
        console.log('User cancelled the cancellation');
      });
    },

    handleCustomerSearch() {
      this.customerPage = 1
      this.debouncedSearch()
    },

    handleCustomerPageChange(page) {
      this.customerPage = page
      this.loadCustomerList()
    },

    handleCustomerSelect(customerId) {
      this.selectedCustomerId = customerId
    },

    // Handle period selection
    handlePeriodSelect(periodId) {
      // TODO: Implement logic for handling period selection
      console.log('Selected period:', periodId);
    },

    // Format period label for display
    formatPeriodLabel(period) {
      if (period.periodEndTime) {

        const end = new Date(period.periodEndTime).toLocaleDateString();
        return `结算记录：${end}`;
      }
      return period.title || period.docCode || period.id;
    },

    // Handle settlement button click
    handleSettlement() {
      this.settlementDialogVisible = true;
    },
    // Handle settlement start event from dialog
    onStartSettlement(formData) {
      // TODO: Implement actual settlement logic
      ElMessageBox.confirm(
        '确定要开始结算吗？结算后数据将被归档，同时会以计算后的存欠料，存欠款作为新周期起始数据。',
        '确认结算',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {

        console.log('Starting settlement with data:', formData);

        let order = PeriodSettlementOrder.empty();
        order.periodEndTime = new Date(formData.endDate);
        order.minRecordCount = formData.minRecords;

        let ret = await this.settlementUiAction.settleCombineOrder(order);

        // Actual settlement logic would go here
        if (ret != null) {
          ElMessage.success('结算成功');
          this.settlementDialogVisible = false;
          this.loadPeriodList();
          this.$refs.excelPage.updateTargetObj(this.selectedCustomer,true);
          
        }

      }).catch((e) => {
        // User cancelled
        console.log('Settment exception:' + e);
        ElMessage.error('结算失败');
      });
    },

    // Handle dialog close event
    onDialogClose() {
      // Reset form data if needed
    }
  }
}
</script>

<style scoped>
.metal-transaction-container {
  padding: 5px;
  height: calc(100vh - 90px);
  background-color: #f5f7fa;
}

.customer-list-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.customer-list-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.period-history-section {
  margin-bottom: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.period-history-section .section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 2px;
}

.customer-search {
  margin-bottom: 15px;
}

.customer-scrollbar {
  flex: 1;
  overflow-y: auto;
  /* 让内容超出时出现滚动条 */
}

.customer-menu {
  border-right: none;
}

.customer-menu .el-menu-item {
  height: 50px;
  line-height: 50px;
}

.customer-menu .el-menu-item:hover {
  background-color: #ecf5ff;
}

.customer-menu .el-menu-item.is-active {
  background-color: #e6f3ff;
  color: #409eff;
}

.customer-pagination {
  padding: 5px 0;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

/* Settlement Section Styles */
.settlement-section {
  margin-top: 10px;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

.settlement-section .section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.transaction-panel {
  height: 100%;
  overflow: hidden;
  /* Prevent panel from expanding beyond container */
}


.transaction-content {
  flex: 1;
  overflow: auto;
  /* Enable scrolling when content exceeds container */
}


.empty-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>